﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EasyBlog.Models;

namespace EasyBlog.Controllers
{
    public class HomeController : Controller
    {
        private readonly DbWlh db;

        public HomeController(DbWlh context)
        {
            db = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult GetList(int pageNo)
        {
            try
            {
                int pageSize = 50;
                //var items = db.InfoBlogs.OrderByDescending(ii => ii.DTCreate).Select(ii => new { ii.ID, ii.Title, ii.UserName, ii.VisitCount }).Skip(pageNo*pageSize).Take(pageSize+1);
                var items = db.InfoBlogs.OrderByDescending(ii => ii.DTCreate).Select(ii => new { ii.ID, ii.Title, ii.UserName, ii.VisitCount });



                return Json(new { code = 1, message = items.Take(pageSize).ToList(), hasMore = items.Count() > pageSize });

            }
            catch (Exception ex)
            {
                return Json(new { code = 0, message = ex.Message });
            }
        }
        public IActionResult Detail(int id)
        {
            var item = db.InfoBlogs.Find(id);
            item.VisitCount++;
            db.SaveChanges();
            ViewBag.Item = item;
            var items = db.InfoReplies.Where(ii => ii.BlogID == id).ToList();

            return View(items);
        }
        [HttpPost]
        public IActionResult Save(int id, string content)
        {
            InfoReply item = new InfoReply
            {
                BlogID = id,
                Content = content,
                DTCreate = DateTime.Now,
                UserName = User.Identity.Name
            };
            db.InfoReplies.Add(item);
            db.SaveChanges();
            return Json(new { code = 1 });
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
